package com.acme.ioniolab.transportfile.implementation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

import com.acme.ioniolab.transportfile.Client;

public class NIOClient implements Client {

	@Override
	public void transportFile(String fileName, String host, int port) throws IOException {
		File in = new File(fileName);

		if (!in.exists()) {
			throw new IOException("File doesn't exist");
		}

		try (SocketChannel socket = SocketChannel.open();
				FileChannel inputChannel = new FileInputStream(in).getChannel();) {

			socket.connect(new InetSocketAddress(host, port));

			ByteBuffer bytes = ByteBuffer.allocate(1024);
			
			bytes.putLong(in.length());
			bytes.rewind();
			socket.write(bytes);
			bytes.clear();
			int readBytes = 0;
			while ((readBytes = inputChannel.read(bytes)) != -1 || bytes.position() > 0) {
				bytes.flip();
				socket.write(bytes);
				bytes.compact();
			}
		}
	}

}
